const express = require("express");
const app = express();
const mysql = require("mysql");
const appid = 'wx3a23de6f2ee0ebca';
const secret = '5aecfcd57d1227dfe9df225e8f62c7e7';
const jwt = require("./utils/jwt")
const bodyParser = require('body-parser')
const request = require('request');
var openids = "";
var flagg = 0;


// body 解析中间件
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
// 创建连接
const db = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: "umbrella",
    dateStrings: true
})
db.connect((err) => {
    if (err) throw err;
    console.log('连接成功');
})

//登录模块
//通过wx.login接口获取code既jscode，传递到后端
//微信小程序中调用API获取code,开发者需要将 code 发送到开发者服务器后台，使用code 换取 session_key api，将 code 换成 openid 和 session_key
app.post("/auth/wechat/login", (req, res) => {
    
    if (req.body.wechat_code) {
        let options = {
            method: 'POST',
            url: 'https://api.weixin.qq.com/sns/jscode2session?',
            formData: {
                appid: appid,
                secret: secret,
                js_code: req.body.wechat_code,
                grant_type: 'authorization_code'
            }
        };
        request(options, (error, response, body) => {
            if (error) { //请求异常时，返回错误信息
                res.json({
                    "status": "error",
                    "code": "请求异常时，返回错误信息"
                })
            } else {
                var strToObj = JSON.parse(body);
                var openid = strToObj.openid;
                openids = openid;
                let tempToken = jwt.createToken(openid);
                let restult = { data: { access_token: tempToken }, success: true };
                res.send(restult)
                let sql = "select count(*) as num from users where ?";
                let post = { openid: openid }
                db.query(sql, post, (err, data) => {
                    if (err) {
                        console.log("数据库连接失败")
                    } else {
                        var object = JSON.stringify(data)
                        if (!(JSON.parse(object)[0]['num'])) {
                            let sql = `insert into users (openid) values('${openid}')`;
                            db.query(sql, (err, data) => {
                            })
                        }
                    }
                })
            }
        });
    } else {
        res.json({
            "status": "error",
            "code": "0004"
        });
    }

})

//是否交押金
app.get("/users/checkDeposit", (req, res) => {
    let sql = `select guarantee from users where openid='${openids}'`;
    db.query(sql, (err, data) => {
        if (err) {
            res.send({ code: 500, data, msg: '新增失败' })
        } else {
            let guarantees = JSON.parse(JSON.stringify(data));
            let datae = guarantees[0].guarantee
            res.send({ data: datae });
        }
    })

})

//进行支付押金
app.put("/users/payDeposit", (req, res) => {
    let sqll = `update users set balance=balance-100 where openid ='${openids}'`;
    db.query(sqll, (err, data) => {
    })
    let sql = `update users set guarantee=guarantee+100 where openid ='${openids}'`;
    db.query(sql, (err, data) => {
        if (err) {
            res.send({ code: 500, data, msg: '新增失败' })
        } else {
            let data = { success: true }
            res.send(data)
        }
    })
})




//是否有正在进行的订单  统计时间的
app.get("/orders/proceedOrders", (req, res) => {
    
    let restult = { data: {startTime: '', endTime:''}, code: 23011 };
    if (flagg<1) {
        let sql = `update users set startTime=now() , endTime=now() where openid='${openids}'`;
        db.query(sql, (err, data) => {
        })
        flagg++;
        
    }else{
        let sqlllll = `update users set endTime=now() where openid ='${openids}'`;
        db.query(sqlllll, (err, data) => {
        })
        
    }

    let sqlll = `select startTime from users where openid='${openids}'`;
        db.query(sqlll, (err, data) => {
            if (err) {
                res.send({ code: 500, data, msg: '新增失败' })
            } else {
                let startTimes = JSON.parse(JSON.stringify(data));
                let datae = startTimes[0].startTime;
                restult.data.startTime = datae;
            }
        })
        let sqllll = `select endTime from users where openid='${openids}'`;
        db.query(sqllll, (err, data) => {
            if (err) {
                res.send({ code: 500, data, msg: '新增失败' })
            } else {
                let endTimes = JSON.parse(JSON.stringify(data));
                let datae = endTimes[0].endTime;
                restult.data.endTime = datae;
                res.send(restult);
            }
        })

    
    
})



//是否有正在进行的订单
app.get("/orders/proceedOrder", (req, res) => {
    
    let restult = { data: { umbrellaId: '', startTime: '', id: 0 ,endTime:''}, code: 23011 };
    // if (flagg<2) {
    //     let sql = `update users set startTime=now() , endTime=now() where openid='${openids}'`;
    //     db.query(sql, (err, data) => {
    //     })
    //     flagg++;
    //     console.log("开始",flagg)
    // }else{
    //     let sqlllll = `update users set endTime=now() where openid ='${openids}'`;
    //     db.query(sqlllll, (err, data) => {
    //     })
    //     console.log("结束",flagg)
    // }
    let sqll = `select umbrellaId from users where openid='${openids}'`;
    db.query(sqll, (err, data) => {
        if (err) {
            res.send({ code: 500, data, msg: '新增失败败' })
        } else {
            let umbrellaIds = JSON.parse(JSON.stringify(data));
            let datae = umbrellaIds[0].umbrellaId;
            restult.data.umbrellaId = datae;

        }
    })
    // let sqlll = `select startTime from users where openid='${openids}'`;
    // db.query(sqlll, (err, data) => {
    //     if (err) {
    //         res.send({ code: 500, data, msg: '新增失败' })
    //     } else {
    //         let startTimes = JSON.parse(JSON.stringify(data));
    //         let datae = startTimes[0].startTime;
    //         restult.data.startTime = datae;
    //     }
    // })
    // let sqllll = `select endTime from users where openid='${openids}'`;
    // db.query(sqllll, (err, data) => {
    //     if (err) {
    //         res.send({ code: 500, data, msg: '新增失败' })
    //     } else {
    //         let endTimes = JSON.parse(JSON.stringify(data));
    //         let datae = endTimes[0].endTime;
    //         restult.data.endTime = datae;
    //     }
    // })
    let sqls = `select id from users where openid='${openids}'`;
    db.query(sqls, (err, data) => {
        if (err) {
            res.send({ code: 500, data, msg: '新增失败' })
        } else {
            let ids = JSON.parse(JSON.stringify(data));
            let datae = ids[0].id;
            restult.data.id = datae;
            res.send(restult);
        }
    })
})

//是否有待支付的订单
app.get("/orders/unpaidOrder", (req, res) => {
    let restult = { data: { cost: 0, id: 0 }, code: 23013, success: true };
    let sqls = `select id from users where openid='${openids}'`;
    db.query(sqls, (err, data) => {
        if (err) {
            res.send({ code: 500, data, msg: '新增失败' })
        } else {
            let ids = JSON.parse(JSON.stringify(data));
            let datae = ids[0].id;
            restult.data.id = datae;
        }
    })
    let sql = `select cost from users where openid='${openids}'`;
    db.query(sql, (err, data) => {
        if (err) {
            res.send({ code: 500, data, msg: '新增失败' })
        } else {
            let costs = JSON.parse(JSON.stringify(data));
            let datae = costs[0].cost;
            restult.data.cost = datae;
            res.send(restult);
        }
    })

})

//查看当前用户的余额和押金的接口
app.get("/my/wallet", (req, res) => {
    let restult = { data: { balance: '', deposit: 0 } };
    let sql = `select balance from users where openid='${openids}'`;
    db.query(sql, (err, data) => {
        if (err) {
            res.send({ code: 500, data, msg: '新增失败' })
        } else {
            let balances = JSON.parse(JSON.stringify(data));
            let datae = balances[0].balance;
            restult.data.balance = datae;

        }
    })
    let sqll = `select guarantee from users where openid='${openids}'`;
    db.query(sqll, (err, data) => {
        if (err) {
            res.send({ code: 500, data, msg: '新增失败' })
        } else {
            let guarantees = JSON.parse(JSON.stringify(data));
            let datae = guarantees[0].guarantee;
            restult.data.deposit = datae;
            res.send(restult);
        }
    })
    // console.log(restult);
})

//选择金额充值
app.post("/users/payAccount", (req, res) => {
    let sql = `update users set balance=balance+${req.body.payAmount} where openid ='${openids}'`;
    db.query(sql, (err, data) => {
        if (err) {
            res.send({ code: 500, data, msg: '新增失败' })
        } else {
            let data = { success: true }
            res.send(data)
        }
    })
})

//取押金
app.put("/users/backDeposit", (req, res) => {
    let sql = `update users set guarantee=0 where openid ='${openids}'`;
    db.query(sql, (err, data) => {
        if (err) {
            res.send({ code: 500, data, msg: '新增失败' })
        } else {
            let data = { success: true }
            res.send(data)
        }
    })
    let sqll = `update users set balance=balance+100 where openid ='${openids}'`;
    db.query(sqll, (err, data) => {
    })
})

//输入雨伞编号
app.post("/orders/placeOrder", (req, res) => {
    let sql = `update users set umbrellaId='${req.body.umbrellaId}' where openid ='${openids}'`;
    db.query(sql, (err, data) => {
        if (err) {
            res.send({ code: 500, data, msg: '新增失败败' })
        } else {
            let data = { success: true }
            res.send(data)
        }
    })
})

//结束用伞
app.post("/orders/finish", (req, res) => {
    flagg = 0;
    let sql = `update users set umbrellaId=null where openid ='${openids}'`;
    db.query(sql, (err, data) => {
        if (err) {
            res.send({ code: 500, data, msg: '新增失败' })
        } else {
            let data = { success: true }
            res.send(data)
        }
    })

  
    
})

//支付金额
app.post("/orders/pay", (req, res) => {
    let sql = `update users set balance=balance-1 where openid ='${openids}'`;
    db.query(sql, (err, data) => {
        if (err) {
            res.send({ code: 500, data, msg: '新增失败' })
        } else {
            let data = { success: true, message: "下次光临" }
            res.send(data)
        }
    })
})
app.listen(3000, () => {
    console.log("服务器开启在3000端口....");
})